// 从一批服务器中找到最快的服务器
package fastest

import (
	"sort"
	"sync"
)

type Fastest struct {
	Host string
	Name string
	Err  error
	Ms   int64
}

type Group struct {
	list []*Fastest
}

func (m *Group) Add(host string, name string) *Group {
	f := new(Fastest)
	f.Name = name
	f.Host = host
	m.list = append(m.list, f)
	return m
}

// 找到最快的服务器
func (m *Group) FindFastest(cb func(*Fastest) (int64, error)) *Group {
	group := sync.WaitGroup{}
	for _, f := range m.list {
		group.Add(1)
		go func(f *Fastest) {
			defer group.Done()
			f.Ms = 0x7FFFFFFF
			ms, err := cb(f)
			if err != nil {
				f.Err = err
				return
			}
			f.Ms = ms
		}(f)
	}
	group.Wait()
	sort.Slice(m.list, func(i, j int) bool {
		return m.list[i].Ms < m.list[j].Ms
	})
	return m
}

/**
 * @description: 获取列表
 * @return {*}
 */
func (m *Group) GetList() []*Fastest {
	return m.list
}

/**
 * @description: 获取最快的服务器
 * @return {*}
 */
func (m *Group) GetFastest() *Fastest {
	if len(m.list) == 0 {
		return nil
	}
	return m.list[0]
}
